package com.demo.youxuanmall.config;

import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class RememberMeInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("user") != null) {
            return true;
        }
        // 检查Cookie
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if ("rememberMe".equals(cookie.getName())) {
                    String username = cookie.getValue();
                    User user = userService.getByUsername(username);
                    if (user != null) {
                        request.getSession().setAttribute("user", user);
                        return true;
                    }
                }
            }
        }
        return true;
    }
} 